#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
同步交易日期客户端程序
用于访问指定日期前160天的数据
"""

import requests
import datetime
import time
from typing import List, Dict, Any
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('sync_trade_date.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class SyncTradeDateClient:
    """同步交易日期客户端"""
    
    def __init__(self, base_url: str = "http://192.168.31.188:8131"):
        """
        初始化客户端
        
        Args:
            base_url: API基础URL
        """
        self.base_url = base_url
        self.session = requests.Session()
        # 设置请求超时时间
        self.session.timeout = 30
        
    def generate_date_range(self, end_date: str, days_back: int = 160) -> List[str]:
        """
        生成日期范围
        
        Args:
            end_date: 结束日期 (格式: YYYY-MM-DD)
            days_back: 向前推多少天
            
        Returns:
            日期列表
        """
        try:
            end_dt = datetime.datetime.strptime(end_date, "%Y-%m-%d")
            date_list = []
            
            for i in range(days_back):
                current_date = end_dt - datetime.timedelta(days=i)
                date_str = current_date.strftime("%Y-%m-%d %H:%M:%S")
                date_list.append(date_str)
                
            return date_list
        except ValueError as e:
            logger.error(f"日期格式错误: {e}")
            return []
    
    def build_request_url(self, shop_code: str, tenant: str, date: str) -> str:
        """
        构建请求URL
        
        Args:
            shop_code: 店铺代码
            tenant: 租户
            date: 日期
            
        Returns:
            完整的请求URL
        """
        from urllib.parse import quote
        encoded_date = quote(date)
        return f"{self.base_url}/syncTradeDate?shopCode={shop_code}&tenant={tenant}&date={encoded_date}"
    
    def send_request(self, url: str) -> Dict[str, Any]:
        """
        发送HTTP请求
        
        Args:
            url: 请求URL
            
        Returns:
            响应结果
        """
        try:
            logger.info(f"发送请求: {url}")
            response = self.session.get(url)
            response.raise_for_status()
            
            result = {
                'status_code': response.status_code,
                'url': url,
                'response': response.text,
                'success': True
            }
            logger.info(f"请求成功: {response.status_code}")
            return result
            
        except requests.exceptions.RequestException as e:
            logger.error(f"请求失败: {e}")
            return {
                'status_code': getattr(e.response, 'status_code', None) if hasattr(e, 'response') else None,
                'url': url,
                'error': str(e),
                'success': False
            }
    
    def sync_trade_dates(self, shop_code: str, tenant: str, end_date: str, 
                        days_back: int = 160, delay: float = 0.1) -> List[Dict[str, Any]]:
        """
        同步交易日期数据
        
        Args:
            shop_code: 店铺代码
            tenant: 租户
            end_date: 结束日期
            days_back: 向前推多少天
            delay: 请求间隔时间(秒)
            
        Returns:
            所有请求的结果列表
        """
        logger.info(f"开始同步交易日期数据: 店铺={shop_code}, 租户={tenant}, 结束日期={end_date}, 天数={days_back}")
        
        # 生成日期范围
        date_list = self.generate_date_range(end_date, days_back)
        if not date_list:
            logger.error("无法生成日期范围")
            return []
        
        results = []
        total_dates = len(date_list)
        
        for i, date in enumerate(date_list, 1):
            logger.info(f"处理进度: {i}/{total_dates} - 日期: {date}")
            
            # 构建URL
            url = self.build_request_url(shop_code, tenant, date)
            
            # 发送请求
            result = self.send_request(url)
            results.append(result)
            
            # 添加延迟避免请求过于频繁
            if i < total_dates:
                time.sleep(delay)
        
        # 统计结果
        success_count = sum(1 for r in results if r['success'])
        logger.info(f"同步完成: 成功 {success_count}/{total_dates} 个请求")
        
        return results
    
    def save_results(self, results: List[Dict[str, Any]], filename: str = "sync_results.txt"):
        """
        保存结果到文件
        
        Args:
            results: 结果列表
            filename: 文件名
        """
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(f"同步交易日期结果报告\n")
                f.write(f"生成时间: {datetime.datetime.now()}\n")
                f.write(f"总请求数: {len(results)}\n")
                f.write(f"成功请求数: {sum(1 for r in results if r['success'])}\n")
                f.write(f"失败请求数: {sum(1 for r in results if not r['success'])}\n\n")
                
                for i, result in enumerate(results, 1):
                    f.write(f"请求 {i}:\n")
                    f.write(f"  URL: {result['url']}\n")
                    f.write(f"  状态码: {result['status_code']}\n")
                    f.write(f"  成功: {result['success']}\n")
                    if result['success']:
                        f.write(f"  响应: {result['response'][:200]}...\n")
                    else:
                        f.write(f"  错误: {result['error']}\n")
                    f.write("\n")
            
            logger.info(f"结果已保存到: {filename}")
            
        except Exception as e:
            logger.error(f"保存结果失败: {e}")


def main():
    """主函数"""
    # 配置参数
    SHOP_CODE = "0007910F7554787"
    TENANT = "1"
    END_DATE = "2025-06-26"
    DAYS_BACK = 160
    BASE_URL = "http://192.168.31.188:8131"
    
    # 创建客户端
    client = SyncTradeDateClient(BASE_URL)
    
    # 执行同步
    results = client.sync_trade_dates(
        shop_code=SHOP_CODE,
        tenant=TENANT,
        end_date=END_DATE,
        days_back=DAYS_BACK,
        delay=0.1  # 100ms延迟
    )
    
    # 保存结果
    client.save_results(results)
    
    # 打印摘要
    success_count = sum(1 for r in results if r['success'])
    print(f"\n同步完成!")
    print(f"总请求数: {len(results)}")
    print(f"成功请求数: {success_count}")
    print(f"失败请求数: {len(results) - success_count}")
    print(f"成功率: {success_count/len(results)*100:.2f}%")


if __name__ == "__main__":
    main() 